<template>
  <!-- 自动投放列表 -->
  <div class="advert-search-word-wrap table-gl-w">
    <div class="search-w table-filter-form">
      <div class="filter-list flex-c">
        <template v-for="(item, i) in filterItem" :key="i">
          <div class="filter-item">
            <template v-if="item.type == 'input_keyword'">
              <filterKeyword :currentItem="item" @search="searchKeyword($event, item)" />
            </template>
            <template v-else-if="item.type == 'input_keyword_type'">
              <filterKeywordByType :currentItem="item" @search="searchKeyword($event, item)" />
            </template>
            <template v-else-if="item.key == 'portfolioIds'">
              <PortfolioIdsMultiple :key="item.key" :info="item" :defaultVal="item.value" @change="selectMulVal($event, item)" />
            </template>
            <template v-else-if="item.key == 'campaignIds'">
              <CampaignIdsMultiple :key="item.key" :info="item" :defaultVal="item.value" @change="selectMulVal($event, item)" />
            </template>
            <template v-else-if="item.key == 'adGroupIds'">
              <AdGroupIdsMultiple :key="item.key" :shopId="advertStore && advertStore.currentShop ? advertStore.currentShop.shopId : ''" :info="item" :defaultVal="item.value" @change="selectMulVal($event, item)" />
            </template>
            <template v-else-if="item.type == 'select_multiple'">
              <selectMultiple :key="item.key" :info="item" :defaultVal="item.value" @change="selectMulVal($event, item)" />
            </template>
            <template v-else-if="item.type == 'select'">
              <a-select v-model="item.value" :style="{ width: item.width + 'px' }" :placeholder="item.placeholder || item.label" allow-clear @change="setSearchVal">
                <a-option v-for="(option, s) in item.optionItems" :key="s" :value="option.value" :label="option.label" />
              </a-select>
            </template>
            <template v-else-if="item.type == 'date_range'">
              <a-range-picker v-model="item.value" :="item.attrs" :disabledDate="disabledDate" :style="{ width: item.width + 'px' }" :allow-clear="false" shortcuts-position="left" :shortcuts="rangeShortcuts()" @change="setSearchVal" />
            </template>
          </div>
        </template>
        <!-- 气泡 -->
        <a-popover trigger="click" ref="selectMulRef" position="bottom" @popup-visible-change="popupVisibleChange">
          <template #content>
            <ul class="target-filter-w">
              <li class="flex-c" v-for="(item, i) in extendMetricsSearches" :key="i">
                <span class="label">{{ AdTargetKeys[item.field] }}：</span>
                <a-input-number v-model="item.minValue" style="width: 120px" placeholder="请输入" size="small">
                  <template #suffix>
                    <span class="unit">{{ item.unit }}</span>
                  </template>
                </a-input-number>
                <span class="line">—</span>
                <a-input-number v-model="item.maxValue" style="width: 120px" placeholder="请输入" size="small">
                  <template #suffix>
                    <span class="unit">{{ item.unit }}</span>
                  </template>
                </a-input-number>
              </li>
            </ul>
            <div class="flex-c-end" style="margin-top: 20px">
              <a-space>
                <a-button size="mini" @click="closePopover">取消</a-button>
                <a-button type="primary" size="mini" @click="setTargetFilter">确认</a-button>
              </a-space>
            </div>
          </template>
          <a-button class="gray-outline filter-item">
            <template #icon>
              <icon-filter />
            </template>
          </a-button>
        </a-popover>
        <div class="filter-item">
          <a-button @click="resetAll">重置</a-button>
        </div>
      </div>
      <div class="filter-result" v-show="resultTags.length > 0 || metricsSearchesReault.length > 0">
        <a-space wrap>
          <a-tag v-for="item in resultTags" size="small" color="arcoblue" closable :key="item.key" @close="delTag(item, 1)">
            <template v-if="!(item.tagVal instanceof Array && item.tagVal.length > 2)">
              <span> {{ item.label }}：</span>
              <p>{{ item.tagVal instanceof Array ? item.tagVal?.join(',') : item.tagVal }}</p>
            </template>
            <a-popover v-else position="bottom">
              <div class="flex-c">
                <span> {{ item.label }}：</span>
                <p>{{ item.tagVal[0] }}，{{ item.tagVal[1] }}等{{ item.tagVal.length }}项</p>
              </div>
              <template #content>
                <p v-for="(val, j) in item.tagVal" :key="j">{{ val }}</p>
              </template>
            </a-popover>
          </a-tag>
          <a-tag v-for="item in metricsSearchesReault" size="small" color="arcoblue" closable :key="item.field" @close="delTag(item, 2)">
            <span> {{ AdTargetKeys[item.field] }}：</span>
            <p v-if="(item.minValue || item.minValue === 0) && (item.maxValue || item.maxValue === 0)">{{ item.minValue }}-{{ item.maxValue }}</p>
            <p v-else-if="item.minValue || item.minValue === 0">>={{ item.minValue }}</p>
            <p v-else>&lt;={{ item.maxValue }}</p>
          </a-tag>
          <a-button type="text" style="color: #000430" v-if="resultTags.length + metricsSearchesReault.length > 1" size="mini" @click="resetAll">清除全部</a-button>
        </a-space>
      </div>
    </div>
    <a-scrollbar style="flex: 1; overflow-y: auto; height: 100%">
      <!-- 图表 -->
      <AdChart ref="adChartRef" type="targeting" :searchParams="searchParam" />
      <!-- 自动投放列表 -->
      <TargetingTable ref="targetingTableRef" :type="type" :searchParams="searchParam" @toCampaign="toCampaign" />
    </a-scrollbar>
  </div>
</template>
<script lang="ts" setup>
  import { FilterTableItem } from '@/types/components'
  import selectMultiple from '@/components/Form/selectMultiple.vue'
  import PortfolioIdsMultiple from './components/portfolioIdsMultiple.vue'
  import CampaignIdsMultiple from './components/campaignIdsMultiple.vue'
  import AdGroupIdsMultiple from './components/adGroupIdsMultiple.vue'
  import TargetingTable from './components/targetingTable.vue'
  import AdChart from './components/adChart.vue'
  import { getStartAndEndTime, rangeShortcuts } from '../common'
  import { AdTargetKeys } from '../types'
  import { ref, onMounted, nextTick } from 'vue'
  import useAdvertStore from '@/store/modules/advert'
  import useBaseDataStore from '@/store/modules/base-data'
  import dayjs from 'dayjs'
  onMounted(async () => {
    await getShopList()
    setFilterItem()
    setSearchVal()
  })
  const props = defineProps({
    markedtList: {
      type: Array,
      default: () => [],
    },
    shopList: {
      type: Array,
      default: () => [],
    },
    userList: {
      type: Array,
      default: () => [],
    },
    type: {
      type: String,
    },
  })

  const emit = defineEmits(['toCampaign'])
  const advertStore = useAdvertStore()
  const filterItem = ref<Array<FilterTableItem>>([])
  // 指标范围过滤
  const extendMetricsSearches = ref<Array<any>>([{ field: 'impressions' }, { field: 'clicks' }, { field: 'ctr', unit: '%' }, { field: 'cost' }, { field: 'cpc' }, { field: 'purchasesOrder' }])
  const resultTags = ref<any>([])
  const selectMulRef = ref()
  const searchParam = ref<any>({
    campaignId: advertStore.currentCampaign?.campaignId,
  })
  const targetingTableRef = ref()
  const adChartRef = ref()
  const metricsSearchesReault = ref<Array<any>>([])
  const useBaseData = useBaseDataStore()
  const shopList = ref<Array<any>>([])

  // 获取店铺
  async function getShopList() {
    await useBaseData.getShopList()
    shopList.value = useBaseData.shopList
  }
  // 设置查询条件
  function setFilterItem() {
    filterItem.value = [
      ...(!props.type
        ? [
            {
              key: 'marketplaceIds',
              label: '站点',
              value: ref(),
              type: 'select_multiple',
              width: 120,
              optionItems: props.markedtList.map((el: any) => {
                return {
                  label: el.marketplaceName,
                  value: el.marketplaceId,
                }
              }),
            },
            {
              key: 'shopIds',
              label: '全部店铺',
              value: ref(),
              type: 'select_multiple',
              width: 120,
              optionItems: shopList.value.map((el: any) => {
                return {
                  label: el.shopName,
                  value: el.id,
                }
              }),
            },
            {
              key: 'portfolioIds',
              label: '广告组合',
              value: ref(),
              type: 'select_multiple',
              width: 120,
              optionItems: [],
            },
            {
              key: 'campaignIds',
              label: '广告活动',
              value: ref(),
              type: 'select_multiple',
              width: 120,
              optionItems: [],
            },
          ]
        : []),
      ...(props.type === 'adGroup'
        ? []
        : [
            {
              key: 'adGroupIds',
              label: '广告组',
              value: ref(),
              type: 'select_multiple',
              width: 120,
              optionItems: [],
            },
          ]),
      {
        key: 'states',
        label: '投放状态',
        value: ref(),
        type: 'select_multiple',
        width: 120,
        optionItems: [
          {
            label: '投放中',
            value: 'ENABLED',
          },
          {
            label: '已暂停',
            value: 'PAUSED',
          },
        ],
      },
      {
        key: 'targetingExpressionTypes',
        label: '投放组',
        value: ref(),
        type: 'select_multiple',
        width: 120,
        optionItems: [
          {
            label: '紧密匹配',
            value: 'QUERY_HIGH_REL_MATCHES',
          },
          {
            label: '同类商品',
            value: 'ASIN_SUBSTITUTE_RELATED',
          },
          {
            label: '关联商品',
            value: 'ASIN_ACCESSORY_RELATED',
          },
          {
            label: '宽泛匹配',
            value: 'QUERY_BROAD_REL_MATCHES',
          },
        ],
      },
      {
        key: 'date',
        label: '日期',
        value: ref(advertStore.currentSearchTime),
        type: 'date_range',
        width: 240,
        attrs: {
          placeholder: ['开始日期', '结束日期'],
        },
      },
    ]
    let searchVal = advertStore.currentSearchVal || {}
    filterItem.value.forEach((el: any) => {
      // 暂时保留店铺
      if (el.key == 'shopIds') {
        el.value = searchVal[el.key] || el.value
      }
    })
  }
  //禁用时间
  function disabledDate(current) {
    return dayjs(current).isAfter(dayjs().subtract(1, 'day'))
  }
  //查询图表和表格数据
  function startSearch() {
    nextTick(() => {
      targetingTableRef.value.getTableListByVal()
      adChartRef.value.refreshData()
    })
  }
  function toCampaign(row: any) {
    emit('toCampaign', row)
  }
  function searchKeyword(searchVal: any, item: any) {
    item.key = searchVal.code
    item.label = searchVal.label
    item.value = searchVal.value
    setSearchVal(searchVal)
  }
  // 批量选择数据
  function selectMulVal(searchVal: any, item: any) {
    item.value = searchVal
    setSearchVal()
  }
  function setSearchVal(orginVal: any = {}) {
    setResultTags()
    if (props.type == 'campaign' && advertStore.currentCampaign?.campaignId) {
      searchParam.value = {
        campaignIds: [advertStore.currentCampaign.campaignId],
      }
    } else if (props.type == 'adGroup' && advertStore.currentGroup?.adGroupId) {
      searchParam.value = {
        campaignIds: [advertStore.currentCampaign.campaignId],
        adGroupIds: [advertStore.currentGroup.adGroupId],
      }
    } else {
      searchParam.value = {}
    }
    filterItem.value.forEach((el: FilterTableItem) => {
      if (el.key == 'date') {
        searchParam.value.startDate = el.value?.[0]
        searchParam.value.endDate = el.value?.[1]
        advertStore.changeSearchTime([searchParam.value.startDate, searchParam.value.endDate])
      } else if (el.key === 'portfolioIds' && el.value instanceof Array) {
        searchParam.value.portfolioIds = el.value.map((el: any) => el.portfolioId)
      } else if (el.key === 'campaignIds' && el.value instanceof Array) {
        searchParam.value.campaignIds = el.value.map((el: any) => el.campaignId)
      } else if (el.key === 'adGroupIds' && el.value instanceof Array) {
        searchParam.value.adGroupIds = el.value.map((el: any) => el.adGroupId)
      } else if (el.key === 'searchTerm') {
        searchParam.value.keywordIsTheSearchAccurate = orginVal?.searchType == 'exact' ? true : false
        searchParam.value.searchTerm = orginVal?.value
      } else {
        searchParam.value[el.key] = el.value
      }
    })
    if (metricsSearchesReault.value.length) {
      searchParam.value['extendMetricsSearches'] = metricsSearchesReault.value
    }
    advertStore?.changeSearchVal(searchParam.value)
    startSearch()
  }

  function setResultTags() {
    resultTags.value = []
    filterItem.value.forEach((el: FilterTableItem) => {
      let val: any = el.value
      let noVal = val === '' || val === null || val === undefined || (val instanceof Array && val.length === 0)
      if (!noVal) {
        resultTags.value.push({
          ...el,
          tagVal: getTagVal(el),
        })
      }
    })
  }
  // 获取查过结果显示的值
  function getTagVal(item: FilterTableItem) {
    if (item.key === 'portfolioIds' && item.value instanceof Array) {
      return item.value.map((el: any) => el.portfolioName)
    } else if (item.key === 'campaignIds' && item.value instanceof Array) {
      return item.value.map((el: any) => el.campaignName)
    } else if (item.key === 'adGroupIds' && item.value instanceof Array) {
      return item.value.map((el: any) => el.adGroupName)
    } else if (item.value instanceof Array) {
      return item.value.map((str: string) => {
        return enumVal(item.optionItems, item.optionField, str)
      })
    } else {
      return enumVal(item.optionItems, item.optionField, item.value)
    }
  }
  function enumVal(optionItems: any, optionField: any, str: any) {
    if (!optionItems?.length) return str
    let option = optionItems?.find((e: any) => str == e.value)
    return option?.label || str
  }
  function resetAll() {
    filterItem.value.forEach((el: FilterTableItem) => {
      if (el.key == 'date') {
        el.value = ref(getStartAndEndTime('last_30_days'))
      } else {
        el.value = ref()
      }
    })
    metricsSearchesReault.value = []
    setSearchVal()
  }
  function delTag(data: any, type: number) {
    if (type == 1) {
      let index = filterItem.value.findIndex((el: FilterTableItem) => el.key == data.key)
      filterItem.value[index].value = ref()
    } else {
      let index = metricsSearchesReault.value.findIndex((el: any) => el.field == data.field)
      metricsSearchesReault.value.splice(index, 1)
    }
    setSearchVal()
  }
  // 获取其他指标的查询参数
  function setTargetFilter() {
    metricsSearchesReault.value = extendMetricsSearches.value.filter((el: any) => el.maxValue || el.maxValue === 0 || el.minValue || el.minValue === 0)
    setSearchVal()
    closePopover()
  }
  function closePopover() {
    selectMulRef.value.handlePopupVisibleChange(false)
  }
  function popupVisibleChange(status: boolean) {
    if (status) {
      extendMetricsSearches.value.forEach((el: any) => {
        let currentItem = metricsSearchesReault.value.find((item: any) => item.field == el.field)
        el.minValue = currentItem?.minValue
        el.maxValue = currentItem?.maxValue
      })
    }
  }
</script>
<style lang="less" scoped>
  .advert-search-word-wrap {
    height: calc(100vh - @menuAndTabHeight);
  }
  .filter-item {
    margin-right: 8px;
    margin-bottom: 5px;
  }
  .filter-result {
    margin-bottom: 5px;
  }
  .filter-list {
    flex-wrap: wrap;
  }
  .target-filter-w {
    li {
      margin-bottom: 5px;
    }
    .label {
      font-size: 12px;
      color: #888;
      width: 90px;
      text-align: right;
    }
    .unit {
      font-size: 12px;
    }
    .line {
      margin: 0 8px;
      color: #999;
    }
    :deep(.arco-input-suffix) {
      padding: 0;
    }
  }
  .arco-scrollbar {
    flex: 1;
    overflow-y: hidden;
    margin-top: 5px;
  }
</style>
